package com.taiji.dicom4cloud.common.security.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.taiji.dicom4cloud.common.model.entity.SysUser;
import com.taiji.dicom4cloud.common.security.model.CommonUserDetails;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author fanxl
 * @Date 2021/5/20
 **/
public class TokenService {
    private String secret = "taiji@029";

    /**
     * 获取token
     * @param userDetails
     * @return
     */
    public String getToken(CommonUserDetails userDetails){
        Map<String, Object> claims = new HashMap<>(16);
        claims.put(UUID.fastUUID().toString(),userDetails.getUsername());
        return createToken(claims);
    }
    public String getHearToken(HttpServletRequest request){
        String authorization =  request.getHeader("Authorization");
        if(StrUtil.isEmpty(authorization)){
            return authorization;
        }
        authorization = authorization.replace("Bearer ","");
        return authorization;
    }

    public String getUserName(String token){
        Claims claims = parseToken(token);
        for (String key :  claims.keySet()){
            Object value = claims.get(key);
            if(ObjectUtil.isNotNull(value)){
                return (String)value;
            }
        }
        return null;
    }

    public SysUser getUser(String token){
        Claims claims = parseToken(token);
        SysUser user = new SysUser();
       for (String key :  claims.keySet()){
           Map<String ,Object>userMap = (Map<String ,Object>)claims.get(key);
           BeanUtil.copyProperties(userMap,user);
       }
        return user;
    }
    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }
}
